package com.gopay.scheduler.job;

import com.gopay.common.asynexport.constants.AsynexportConstants;
import com.gopay.common.asynexport.service.AsynexportService;
import com.gopay.common.asynexport.vo.AsyncExportInfo;
import com.gopay.common.util.DateUtils;
import com.gopay.common.util.StringTools;
import com.gopay.scheduler.GopayBaseJob;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.StopWatch;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.File;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * Created by Think on 2017/8/30.
 */
@Service("asyncExportFileCleanJob")
public class AsyncExportFileCleanJob extends GopayBaseJob {

    private Logger logger = LoggerFactory.getLogger(AsyncExportFileCleanJob.class);

    @Resource(name = "asynexportService")
    private AsynexportService asynexportService;

    @Override
    protected void doJobInternal() {
        try {
            Calendar calendar = Calendar.getInstance();
            calendar.add(Calendar.DATE,-7);
            Date cleanDate = calendar.getTime();
            String cleanDateStr = DateUtils.formatDate(cleanDate,"yyyyMMdd");
            logger.info("开始清理{}日的文件",cleanDateStr);
            List<AsyncExportInfo> list = asynexportService.findWaitCleanAsynExportList(cleanDateStr);
            if (list != null && !list.isEmpty()) {
                logger.info("待清理的文件数量为:{}",list.size());
                StopWatch sw = new StopWatch();
                sw.start();
                CountDownLatch latch = new CountDownLatch(list.size());
                for (AsyncExportInfo vo : list) {
                    cleanFile(vo);
                }

                sw.stop();
                long spendTime = sw.getTime();
                long sec = spendTime / 1000;
                long ns = spendTime % 1000;
                if (sec > 0) {
                    logger.info("异步导出文件清理完毕,耗时：{}秒{}毫秒", sec, ns);
                } else {
                    logger.info("异步导出文件清理完毕,耗时：{}毫秒", list.size(), ns);
                }
            } else {
                logger.info("没有待清理的文件。");
            }
        } catch (Exception e) {
            logger.error("清理异步导出文件出现异常！", e);
        }
    }

    private void cleanFile(AsyncExportInfo vo) {
        try {
            vo.setDealStatus(AsynexportConstants.DEAL_STATUS_INVALID);
            vo.setLastDealTime(new Date());
            asynexportService.update(vo);

            String filePath = vo.getFilePath();
            String fileName = vo.getFileName();
            if(StringUtils.isBlank(filePath) || StringUtils.isBlank(fileName)) {
                throw new RuntimeException("文件不存在");
            }
            File file = new File(filePath + File.separator + fileName);
            if(file.exists()) {
                file.delete();
            }
        } catch (Exception e) {
            logger.error("处理[{}]的记录出错！",vo.getId(),e);
            vo.setDealStatus(AsynexportConstants.DEAL_STATUS_SUCCESS);
            vo.setLastDealTime(new Date());
            asynexportService.update(vo);
        }
    }
}